package com.lyw.gulimall.product.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyw.common.constant.ProductConstant;
import com.lyw.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.lyw.gulimall.product.dao.AttrDao;
import com.lyw.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.lyw.gulimall.product.entity.AttrEntity;
import com.lyw.gulimall.product.service.AttrService;
import com.lyw.gulimall.product.vo.AttrGroupWithAttrsVo;
import com.lyw.gulimall.product.vo.AttrRelationGroupVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyw.common.utils.PageUtils;
import com.lyw.common.utils.Query;

import com.lyw.gulimall.product.dao.AttrGroupDao;
import com.lyw.gulimall.product.entity.AttrGroupEntity;
import com.lyw.gulimall.product.service.AttrGroupService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public IPage<Map<String, Object>> queryPage(Integer page, Integer limit, Long catelogId, String key) {
        Page<Map<String, Object>> result = new Page<>(page, limit);
        LambdaQueryWrapper<AttrGroupEntity> lqw = new LambdaQueryWrapper<>();
        if (catelogId != 0 && catelogId > 0) {
            lqw.eq(AttrGroupEntity::getCatelogId, catelogId);
        }
        if (StringUtils.isNotBlank(key)) {
            lqw.and((obj) -> {
                obj.eq(AttrGroupEntity::getAttrGroupId, key).or().like(AttrGroupEntity::getAttrGroupName, key);
            });
        }
        IPage<Map<String, Object>> list = baseMapper.selectPageList(result, lqw);
        return list;
    }

    @Override
    public void deleteRelation(AttrRelationGroupVo[] vos) {
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map(item -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);

            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(entities);
    }

    /**
     * 获取当前分组没有关联的所有属性
     * 1.通过分组id获取到分组实体类，在获取到当前分组的分类id
     * 2.通过分组id和分类id找到当前分类的所有分组（排除当前分组），获取到所有的分组id
     * 3.根据当前分类的所有分组id，在属性、分组关系表中找到所有有关联的属性id
     * 4.创建一个属性的类型是基本属性，并且分类的id与当前分类相同的一个条件构造器
     * 5.如果查到的所有属性id不为空，在条件构造器中添加not in 查询到的属性ids
     * 6.如果key不为空添加key到条件构造器中，查询功能
     * 7.通过mybatis的分页功能返回结果
     */
    @Override
    @Transactional
    public IPage<AttrEntity> getAttrNoRelation(Integer page, Integer limit, Long attrgroupId, String key) {

        // 1.当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = baseMapper.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        // 2.当前分组只能关联别的分组没有引用的属性
        // 2.1）当前分类下的其他属性的信息
        List<AttrGroupEntity> attrGroupEntities = baseMapper
                .selectList(new LambdaQueryWrapper<AttrGroupEntity>()
                        // 找到当前分组关联的分类
                        .eq(AttrGroupEntity::getCatelogId, catelogId));
                        // 找到除了当前分组之外， 并且也和 catelogId 分类关联的分组信息
                        // 用于排除关联的属性信息
        List<Long> groupIds = attrGroupEntities.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());

        // 2.2）这些分组关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().in(AttrAttrgroupRelationEntity::getAttrGroupId, groupIds));
        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());

        // 2.3）从当前分类的所有属性中移除这些属性
        LambdaQueryWrapper<AttrEntity> queryWrapper = new LambdaQueryWrapper<AttrEntity>().eq(AttrEntity::getCatelogId, catelogId).eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds.size() != 0) {
            queryWrapper.notIn(AttrEntity::getAttrId, attrIds);
        }
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.and(wrapper -> wrapper.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key));
        }
        IPage<AttrEntity> pages = attrDao.selectPage(new Page<>(page, limit), queryWrapper);
        return pages;
    }

    /**
     * 根据分类id查出当前分类下的所有分组以及分组关联的属性
     * @param catelogId
     * @return
     */
    @Override
    @Transactional
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        // 1、找到所有分组
        List<AttrGroupEntity> groupEntities = baseMapper.selectList(new LambdaQueryWrapper<AttrGroupEntity>().eq(AttrGroupEntity::getCatelogId, catelogId));

        // 2、查到所有的属性
        List<AttrGroupWithAttrsVo> groupWithAttrsVos = groupEntities.stream().map(entity -> {
            AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(entity, vo);
            List<AttrEntity> attrs = attrService.getRelationAttr(entity.getAttrGroupId());

            vo.setAttrs(attrs);
            return vo;
        }).collect(Collectors.toList());
        return groupWithAttrsVos;
    }
}
